//
// Created by xili on 2024/8/27 19:51.
// GO BIG OR GO HOME.
//
#include "leetcode.h"

class Solution {
public:
    long long maximumSubarraySum(vector<int> &nums, int k) {
        long long ans = 0;
        int n = nums.size(), i = 0;
        long long sum = 0;
        unordered_map<int, int> ump;
        for (; i < k - 1; i++) {
            ump[nums[i]]++;
            sum += nums[i];
        }
        for (; i < n; i++) {
            ump[nums[i]]++;
            sum += nums[i];
            if (ump.size() == k) {
                ans = ans > sum ? ans : sum;
            }
            sum -= nums[i - k + 1];
            ump[nums[i - k + 1]]--;
            if (ump[nums[i - k + 1]] == 0) {
                ump.erase(nums[i - k + 1]);
            }
        }
        return ans;
    }
};